<template>
  <div class="base-container">
    <t-sticky-tool
      v-if="formData.projectId"
      :style="{ position: 'fixed', overflow: 'hidden',zIndex: 1000}"
      :offset="[-50, 100]"
      @click="handlerOpenDetail"
    >
      <t-sticky-item style="width: 80px" label="任务书详情">
        <template #icon>
          <t-icon name="file-paste"></t-icon>
        </template>
      </t-sticky-item>
    </t-sticky-tool>
    <t-form ref="form" label-align="top" :data="formData" :colon="true" labelWidth="100px" :rules="rules">
      <t-form-item label="变更项目" name="projectId">
        <t-select v-if="editOpen" style="width: 390px" :disabled="!editOpen" @change="handleProjectChange" clearable
                  v-model="formData.projectId" :options="projectOptions"></t-select>
        <div v-else>{{ formData.contract.projectName }}</div>
      </t-form-item>

      <t-form-item v-if="formData.projectId" label="变更类型" name="changeType">
        <t-select style="width: 390px" :disabled="!editOpen" :options="dict.type.change_type"
                  v-model="formData.changeType"></t-select>
      </t-form-item>
      <!--    <t-form-item v-if="formData.changeType === '1'" label="研究人员变更">-->
      <!--      <project-member  v-model="formData.projectMembers" :projectId="formData.projectId" :showTip="false" :editOpen="editOpen" phaseType="31"></project-member>-->
      <!--    </t-form-item>-->
      <!--    <t-form-item v-else-if="formData.changeType === '2'" label="合作单位变更">-->
      <!--      <project-unit ref="project-unit" :adviceFunding="adviceFunding" v-model="formData.projectCompanys" :projectId="formData.projectId" :editOpen="editOpen" phaseType="31"></project-unit>-->
      <!--    </t-form-item>-->
      <project-member v-if="formData.changeType === '1'" v-model="formData.projectMembers"
                      :projectId="formData.projectId" :showTip="false" :editOpen="editOpen"
                      phaseType="31"></project-member>

      <project-unit v-else-if="formData.changeType === '2'" ref="project-unit" :adviceFunding="adviceFunding"
                    v-model="formData.projectCompanys" :projectId="formData.projectId" :editOpen="editOpen"
                    phaseType="31"></project-unit>

      <t-form-item v-else-if="formData.changeType === '3'" label="">
        <t-form-item label="变更后任务书开始时间" name="contractChangeDate.startDate">
          <t-date-picker :disabled="!editOpen" clearable style="width: 390px"
                         v-model="formData.contractChangeDate.startDate"></t-date-picker>
        </t-form-item>
        <t-form-item label="变更后任务书结束时间" name="contractChangeDate.completeDate">
          <t-date-picker :disabled="!editOpen" clearable style="width: 390px"
                         v-model="formData.contractChangeDate.completeDate"></t-date-picker>
        </t-form-item>
      </t-form-item>
      <t-form-item label="变更说明" name="note">
        <tiny-mce-editor :disabled="!editOpen" v-model="formData.note"></tiny-mce-editor>
      </t-form-item>
      <t-form-item label="审批附件" >
      <t-table size="small" row-key="id" :columns="projectFileColumns" :data="projectFileData">
        <template #id="{row, rowIndex}">
          {{ rowIndex + 1 }}
        </template>
        <template #op="{row}">
          <file-upload v-model="row.fileIds" :moduleKey="row.moduleKey"
                       :fileList="row.fileLists"
                       :multiple="true">
            <t-button variant="outline">
              <t-icon name="cloud-upload" slot="icon"/>
              点击上传
            </t-button>
          </file-upload>
        </template>
        <template #c1="{row}">
          <a v-if="row.c3" class="t-button-link" :href="`${file_domain}/${row.c3}`" target="_blank">{{ row.c1 }}</a>
          <div v-else>{{ row.c1 }}</div>
        </template>
      </t-table>
      </t-form-item>
      <t-row>
        <t-col :span="11" class="query-form-inline">
          <t-button v-if="editOpen" :loading="applyLoading" theme="primary" @click="onSubmit(1)">暂存</t-button>
          <t-tooltip v-if="editOpen" content="提交后不可再编辑会进入审批流程">
            <t-button :loading="applyLoading" theme="primary" @click="onSubmit(2)">提交到单位管理员</t-button>
          </t-tooltip>
        </t-col>
        <t-col :span="1" class="operation-container">
          <t-button variant="outline" @click="close">返回</t-button>
        </t-col>
      </t-row>
    </t-form>
    <contract-detail-dialog :header="dialog.header" :objId="formData.projectId"
                            :visible.sync="dialog.open_contract_detail"
                            v-if="dialog.open_contract_detail"></contract-detail-dialog>

  </div>
</template>

<script>
import { VITE_FILE_DOMAIN } from '@/api/upload'
import projectMember from "../../pm/components/project-member.vue";
import projectUnit from "../../pm/components/project-unit.vue";
import ContractDetailDialog from "../../contract/components/contract-detail-dialog.vue";
import TinyMceEditor from "@/components/TinyMceEditor/index.vue";
import {getFiles} from "@/api/common";
import FileUpload from "@/components/FileUpload/index.vue"

export default {
  name: "add-edit-change-apply",
  components: {
    projectMember,
    projectUnit,
    ContractDetailDialog,
    TinyMceEditor,
    FileUpload
  },
  dicts: ['change_type'],
  props: {
    header: {
      type: String,
    }
  },

  data() {
    return {
      site_tag: import.meta.env.VITE_SITE_TAG,
      file_domain: VITE_FILE_DOMAIN,
      projectFileData: [
        {
          id: 1,
          c1: "项目变更申请表(盖章件)",
          c2: "是",
          moduleKey: "XMBGSQB",
          fileIds: [],
          fileLists: [],
          require: true,
        },
      ],
      projectFileColumns: [
        {
          colKey: "id",
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "c1",
          title: "附件名称",
          align: "center",
        },

        {
          colKey: "c2",
          title: "是否必需",
          align: "center",
        },
        {
          colKey: "op",
          title: "操作",
          align: "left",
        },
      ],
      dialog: {
        open_contract_detail: false,
        header: "",
        objId: 0,
      },
      applyLoading: false,
      taskId: null,
      objId: null,
      isCommit: false,
      loading: false,
      visible: true,
      editOpen: true,
      formData: {
        projectId: null,
        contractId: null,
        changeType: '',
        projectName: '',
        projectMembers: [],
        projectCompanys: [],
        contractChangeDate: {
          startDate: '',
          completeDate: '',
        },
        contract: {},
        note: '<div style="padding-left: 24pt;" class="mceNonEditable">一、项目进展情况</div><p style="padding-left: 24pt;"></p><p style="padding-left: 24pt;"></p><div style="padding-left: 24pt;" class="mceNonEditable">二、项目变更的内容及理由</div><p style="padding-left: 24pt;"></p><p style="padding-left: 24pt;"></p><div style="padding-left: 24pt;" class="mceNonEditable">三、变更后的进度和经费使用安排</div><p style="padding-left: 24pt;"></p><p style="padding-left: 24pt;"></p>',

      },
      adviceFunding: 0,
      rules: {
        projectId: [
          {
            required: true,
            message: "变更项目不能为空",
          },
        ],
        note: [
          {
            required: true,
            message: "变更说明不能为空",
          },
        ],
        changeType: [
          {
            required: true,
            message: "变更类型不能为空",
          },
        ],
        projectMembers: [
          {
            required: true,
            message: "研究人员不能为空",
          },
        ],
        projectCompanys: [
          {
            required: true,
            message: "合作单位不能为空",
          },
        ],
        'contractChangeDate.startDate': [
          {
            required: true,
            message: "任务书开始时间不能为空",
          },
          {
            validator: (val) => {
              if (val && this.formData.startDate) {
                const startTime = new Date(this.formData.startDate).getTime()
                const endTime = new Date(val).getTime()
                return startTime <= endTime;
              }
              return true;
            }, message: "任务书开始时间不能大于结束时间", type: "error"
          },
        ],
        'contractChangeDate.completeDate': [
          {
            required: true,
            message: "任务书完成时间不能为空",
          },
        ]
      },
      projectOptions: []
    }
  },
  async created() {
    const taskId = this.$route.params && this.$route.params.taskId;
    if (!taskId) {
      this.$message.error("任务id丢失返回");
      this.$router.push("/kjxm/implement/change-apply");
    }
    this.taskId = taskId;
    if (sessionStorage.getItem(`${this.taskId}-changeApply-objId`)) {
      this.objId = Number(sessionStorage.getItem(`${this.taskId}-changeApply-objId`))
      await this.getObj();
    }
    if (sessionStorage.getItem(`${this.taskId}-changeApply-editOpen`) === '0') {
      this.editOpen = false;
    }
    // 获取我的可变更项目列表
    this.changeApplyMyProjectList();
  },
  methods: {
    handlerOpenDetail(val) {
      if (val.item.label === '任务书详情') {
        this.dialog.open_contract_detail = true;
      }
    },
    getObj() {
      return this.$api.kjxm.implement.changeApplyGet(this.objId).then(response => {
        Object.assign(this.formData, response.data)
        this.adviceFunding = response.data.contract.adviceFunding;
        getFiles(this.objId).then((res) => {
          const files = {}
          res.data.forEach((item) => {
            if (!files[item.moduleKey]) {
              files[item.moduleKey] = []
            }
            files[item.moduleKey].push({
              name: item.fileName,
              url: item.fullFilePath,
              id: item.id,
              filePath: item.filePath
            })
          })
          this.projectFileData.forEach((val, index) => {
            this.projectFileData[index].fileLists = files[val.moduleKey] || [];
            this.projectFileData[index].fileIds = files[val.moduleKey]?.map(val => val.id) || [];
          })
        });

      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    handleProjectChange(val, content) {
      this.formData.contractId = content?.option?.contractId;
    },
    changeApplyMyProjectList() {
      this.$api.kjxm.implement.changeApplyMyProjectList().then(response => {
        this.projectOptions = response.data.map(val => {
          return {
            label: val.projectName,
            value: val.id,
            contractId: val.contractId,
          }
        });
        if(this.projectOptions.length<=0 && this.formData.contract){
          this.projectOptions = [{
            label: this.formData.contract.projectName,
            value: this.formData.projectId,
            contractId: this.formData.contract.id,
          }]
        }
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    onSubmit(type) {
      const sysAttMainIds = []
      this.projectFileData.forEach(val => {
        sysAttMainIds.push(...val.fileIds)
      })
      if (type === 1) {
        this.applyLoading = true;
        if (this.objId) {
          this.$api.kjxm.implement.changeApplyUpdate(
            {...this.formData,
            sysAttMainVo: {
              sysAttMainIds,
            }}).then(() => {
            this.$message.success("暂存成功");
            this.applyLoading = false;
          }).catch((e) => {
            this.$message.error(e.toString());
            this.applyLoading = false;
          });
        } else {
          this.$api.kjxm.implement.changeApplyAdd({...this.formData,
            sysAttMainVo: {
              sysAttMainIds,
            }}).then((response) => {
            this.$message.success("暂存成功");
            this.applyLoading = false;
          }).catch((e) => {
            this.$message.error(e.toString());
            this.applyLoading = false;
          });
        }
      } else {
        this.$refs.form.validate().then((validateResult) => {
          if (validateResult === true) {
            if (this.formData.changeType === '2') {
              const isValidate = this.$refs["project-unit"].checkData()
              if (!isValidate) {
                return false;
              }
            }
            const isValidate = this.projectFileData.every(val => {
              if (val.require && val.fileIds.length <= 0) {
                this.$message.error(`附件：需要上传${val.c1}`);
                return false;
              }
              return true
            })
            if (!isValidate) {
              return false
            }
            this.applyLoading = true;
            if (this.objId) {
              this.$api.kjxm.implement.changeApplyUpdate({...this.formData,
                sysAttMainVo: {
                  sysAttMainIds,
                }}).then(() => {
                this.$api.kjxm.implement.changeApplySubmit({id: this.objId}).then(response => {
                  this.$message.success('提交成功');
                  this.applyLoading = false;
                  this.close();
                }).catch((e) => {
                  this.applyLoading = false;
                  this.$message.error(e.toString());
                });
              }).catch((e) => {
                this.applyLoading = false;
                this.$message.error(e.toString());
              });
            } else {
              this.$api.kjxm.implement.changeApplyAdd({...this.formData,
                sysAttMainVo: {
                  sysAttMainIds,
                }}).then((res) => {
                this.$api.kjxm.implement.changeApplySubmit({id: res.data.id}).then(response => {
                  this.$message.success('提交成功');
                  this.applyLoading = false;
                  this.close();
                }).catch((e) => {
                  this.applyLoading = false;
                  this.$message.error(e.toString());
                });
              }).catch((e) => {
                this.applyLoading = false;
                this.$message.error(e.toString());
              });
            }
          } else {
            const firstError = Object.values(validateResult)[0]?.[0]?.message;
            this.$message.error(firstError);
          }
        });
      }

    },
    close() {
      this.$tab.closeOpenPage({path: "/kjxm/implement/change-apply-my"});
    },
  }
}
</script>

<style scoped>

</style>
